import random
from datetime import datetime
from faker import Faker
from django.http.response import HttpResponse, JsonResponse
from .models import Story, StoryTag, StorySubject
from frontuser.models import FrontUser
from utils.random_time import gen_random_time

fake = Faker(locale='zh_CN')


def add_story(request):
    user = FrontUser.objects.first()
    tag, _ = StoryTag.objects.get_or_create(tag='修真')
    # 插入默认分类
    StoryTag.objects.get_or_create(tag='默认分类')
    pub_time_date = gen_random_time().get('date')
    pub_time = datetime.strptime(pub_time_date, '%Y-%m-%d %H:%M:%S').date()
    story = Story(name='完美世界', pub_time=pub_time, front_user=user, tag=tag)
    story.save()
    return HttpResponse('stroy创建成功')


def delete_tag(request):
    StoryTag.objects.filter(tag__exact='修真').delete()
    return HttpResponse('tag标签删除成功')


def add_foreign_key(request):
    # 新增数据
    user = FrontUser.objects.first()
    # tag = StoryTag.objects.filter(tag__exact='修真').first()
    pub_time_date = gen_random_time().get('date')
    pub_time = datetime.strptime(pub_time_date, '%Y-%m-%d %H:%M:%S').date()
    # story = Story(name=fake.sentence(), pub_time=pub_time, front_user=user, tag=tag)
    # story.save()

    # 查询某个分类下所有小说
    tag = StoryTag.objects.filter(tag__exact='修真').first()
    # TODO 未配置related_name='stories'参数前，使用：模型名称小写_set
    # stories = tag.story_set.all()
    stories = tag.stories.all()
    print(stories)

    # 为某个分类添加小说
    story = Story(name=fake.sentence(), pub_time=pub_time, front_user=user)
    tag.stories.add(story, bulk=False)
    return JsonResponse({'code': 200, 'msg': 'success', 'data': None})


def many_to_many(request):
    # TODO 创建主题
    # subjects = StorySubject.objects.all()
    # # for _ in range(5):
    # #     subject = StorySubject(name=fake.job())
    # #     subject.save()
    # # TODO 抽取随机主题
    # sample_subjects = random.sample(list(subjects), random.randint(1, len(subjects)))
    # # TODO 创建小说
    # user = FrontUser.objects.first()
    # pub_time_date = gen_random_time().get('date')
    # pub_time = datetime.strptime(pub_time_date, '%Y-%m-%d %H:%M:%S').date()
    # story = Story(name=fake.sentence(), pub_time=pub_time, front_user=user)
    # story.save()
    # # TODO 添加小说主题
    # story.subjects.add(*sample_subjects)

    # 查询主题下所有小说
    # for subject in subjects:
    #     print(subject.name)
    #     print(subject.stories.all())

    # 查询小说小所有主题
    stories = Story.objects.all()
    for story in stories:
        print(story.name)
        print(story.subjects.all())
    return HttpResponse('添加成功')
